<template>
<!--  房间管理由楼栋管理改写-->
  <div>
    <!--Dialog对话框-->
    <el-dialog
      :title="
        dialogConfig.openType==='add'?
        dialogConfig.addName:dialogConfig.openType==='adds'?
        dialogConfig.addsName:dialogConfig.editName"
      :close-on-click-modal="false"
      :visible.sync="dialogConfig.dialogFormVisible"
    >
      <template></template>
      <!--      Dialog表单-->
      <CommonForm
        ref="my-form"
        :form="dialogForm"
        :formLabel="dialogFormLabel"
        :formConfig="dialogFormLConfig"
      >
      </CommonForm>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialogForm(dialogForm)">确 定</el-button>
        <el-button @click="dialogConfig.dialogFormVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <h3>房间管理</h3>
    <!--    按钮区域-->
    <div class="mainBtn">
      <el-button type="primary" plain size="medium" @click="clickAddData"
      >添 加</el-button>
      <el-button type="primary" plain size="medium" @click="clickAddsData"
      >批量添加</el-button>
      <!--      删除确认提示框-->
      <el-popconfirm
        icon="el-icon-info"
        icon-color="red"
        :title="
        tableSelected.length < 1 ?
      ' 请在表格中选择 '
  : '确认要删除' + tableSelected.length + '条数据？' "
        @confirm="getDeleteReady(tableSelected)"
      >
        <el-button type="danger" slot="reference" plain size="medium"
        >删 除</el-button>
      </el-popconfirm>
      <!--      检索部分-->
      <el-button  type="waring" plain size="medium" @click="searchFormVisible=!searchFormVisible" icon="el-icon-search"
      >检 索</el-button>
      <!-- 显示列 弹出框 -->
      <el-popover placement="top-start" width="200" trigger="click">
        <el-button
          type="info"
          slot="reference"
          plain
          class="showColumnBtn"
          size="medium"
        >显示列</el-button
        >
        <!-- 显示列的多选框 -->
        <el-checkbox-group
          v-model="checkedColumnList"
          @change="handleCheckedColumnChange"
        >
          <el-checkbox
            v-for="item in tableColumnList"
            :label="item.label"
            :key="item.label"
          >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
      </el-popover>
    </div>
    <el-collapse-transition>
      <div v-if="searchFormVisible" class="searchDiv">
        <CommonForm
          :form="searchForm"
          :formLabel="searchLabel"
          :formConfig="searchConfig"
        ></CommonForm>
        <el-button
          type="primary"
          size="mini"
          @click="searchBuilding(searchForm)"
        >搜 索</el-button
        >
        <el-button
          type="danger"
          size="mini"
          @click="resetData"
        >重 置</el-button
        >
      </div>
    </el-collapse-transition>
    <!--      房间表格-->
    <div style="height: 400px;">
      <CommonTable v-loading = "loading"  element-loading-text="拼命加载中"
                   :tableData="tableData"
                   :tableLabel="tableLabel"
                   :tableConfig="tableConfig"

                   @handleSelectionChange="handleSelectionChange"
                   @sizeChange="getTableData(1, tableConfig.size, {})"
                   @currentPage="getTableData(tableConfig.page, tableConfig.size, {})"
      >
        <template v-slot:operation>
          <el-table-column prop="operation" label="操作">
            <template slot-scope="scope">
              <el-tooltip
                :enterable="false"
                class="item"
                content="编辑"
                placement="top"
              >
                <el-button
                  type="primary"
                  size="mini"
                  @click="clickEditData(scope.row)"
                >编辑</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </template>
      </CommonTable>
    </div>
  </div>
</template>

<script>
import CommonManageMain from "components/common/CommonManageMain.vue";
import CommonTable from "components/common/CommonTable.vue";
import CommonForm from "components/common/CommonForm.vue";
import {
  getRoomList,
  addRoom,
  addRooms,
  delRoom,
  editRoom
} from "@/api/schoolManage/roomManage"

import 'element-ui/lib/theme-chalk/base.css';
import {getEquipmentModel} from "@/api/equipmentMange/equipModelManage";
import Vue from "vue";

export default {
  name:"roomManage",
  components: {
    CommonManageMain,
    CommonTable,
    CommonForm
  },
  beforeMount()
  {
//获取学校信息列表
    //this.getSchoolName();
    //初始化表格
    // this.getTableData(1,this.tableConfig.size,{})
    //初始化 显示列 的数据
    this.tableColumnList = this.tableLabel;
    //获取原始数组label
    this.checkedColumnList = this.tableColumnList.map(item => item.label);
    //获取设备型号列表
    this.getEquipment();
  },
  data(){
    return {
      //Dialog
      dialogConfig: {
        openType: "add",
        addName: '添加房间',
        addsName: '批量添加房间',
        editName: '编辑房间',
        dialogFormVisible: false,
      },
      dialogForm: {
        campusName: [

        ],
        buildingName: "",
        roomNumber:"",
        equipmentModel:'',
        deviceID:'',
        remarks: ""
      },
      dialogFormLabel: [
        {
          model: "campusName",
          label: "校区",
          type: "campusCascader",
          width: "70",
        },
        {
          model: "buildingName",
          label: "楼栋",
          width: "70",
          type:'buildingSelect'
        },
        {
          model: "roomNumber",
          label: "房间号",
          width: "70",
        },
        {
          model: "equipmentModel",
          label: "设备型号",
          width: "70",
          type:'select',
          options:[]
        },
        {
          model: "deviceID",
          label: "设备ID",
          width: "70"
        },
        {
          model: "remarks",
          label: "备注",
          type: "textarea",
          rows: 5,
          width: "70"
        }
      ],
      dialogFormLConfig: {
        labelWidth: "100px",
        inline: false,
        labelPosition: "right",
        rule:{
          campusName:[
            {required: true,trigger: 'blur'},
          ],
          buildingName:[
            {required: true,trigger: 'blur'},
          ],
          roomNumber:[
            { required: true, message: '房间号不能为空',trigger: 'blur'},
          ]
        }
      },
      //获取校区及校区名
      roomData:{},
      // Search检索
      searchForm: {
        schoolName: "",//	学校名称
        campusName: "",//	校区名称
        buildingName: "",//楼栋名称
        roomNumber:"",//房间号
        equipmentStatus:"",//设备状态，0限制，1使用
        equipmentIdentifier:""//设备ID
      },
      searchLabel:[
        {
          model: "schoolName",
          label: "学校名称",
        },
        {
          model: "campusName",
          label: "校区名称",
        },
        {
          model: "buildingName",
          label: "楼栋名称",
        },
        {
          model: "roomNumber",
          label:"房间号"
        },
        {
          model: "equipmentStatus",
          label:"设备状态",
          type:'select',
          options:[
            {
              label:"限制",
              value:"0"
            },
            {
              label:"使用",
              value:"1"
            }
          ]
        },
        {
          model: "equipmentIdentifier",
          label:"设备ID"
        },
        {
          model: "equipment",
          label:"设备类型",
          type:"select",
          options:[
            {
              label:'列表缺少数据',
              value:null
            }
          ]
        }
      ],
      searchConfig:
  {
        labelWidth: "80px",
        inline: true,
        labelPosition: "left",
      },
      searchFormVisible:false,
      // Table
      loading: false,//表格载入
      tableData:[
        {
          "schoolName": "城市学院",
          "campusName": "主校区",
          "buildingName": "学1号楼",
          "roomNumber": "515",
          "equipmentStatus": "0",
          "equipmentIdentifier": "110218ww123",
          "remark":'1234567'
        }
      ],//表格数据
      tableLabel:[
        {
          prop:"schoolName",
          label:"学校名称"
        },
        {
          prop:"campusName",
          label:"校区名称"
        },
        {
          prop:"buildingName",
          label:"楼栋名称"
        },
        {
          prop: 'roomNumber',
          label: '房间号'
        },
        {
          prop: 'equipmentStatus',
          label: '设备状态',
          type:'dualJudgment',
          trueType:"使用",
          falseType:'限制'
        },
        {
          prop: 'equipmentIdentifier',
          label: '设备ID'
        }
      ],
      tableConfig:{
        isShowLoading:true,
        //当前页
        page:1,
        total:30,
        //单页条目
        size:10,
        //多选
        selection:true,
        //行唯一辨识值 跨页
        rowKey:"individualId"
      },
      tableSelected:[],//表格选中合集
      checkedColumnList: [],// 显示列选中集合
      tableColumnList: [],//列的集合
    }
  },
  provide: function () {
    return {

    }
  },
  watch:{
    // 当 dialog 关闭时 ，重置表单
    'dialogConfig.dialogFormVisible' (newValue) {
      if(!newValue) {
        this.dialogForm = this.$options.data().dialogForm
      }
    }

  },
  methods:{
    getEquipment(){
      getEquipmentModel(1,10).then(res=>{
        const result = res.data;
        if (result.code == 200){
          const equipmentModelList = result.data.records;
          let myList = [];
          equipmentModelList.forEach(item=>{
            let {equipmentModel:label,equipmentModelId:value} = item;
            myList.push({label,value});
          })
          Vue.set(this.dialogFormLabel[3],'options',myList)
        }
      })
    },
    //-----------------表格------------------
    //获取数据表格
    getTableData(page,pageSize,datas){
      getRoomList(page,pageSize,datas).then(res=>{
        let resultData = res.data;
        if (resultData.code == 200){
          this.loading = false
          this.tableData = resultData.data.records;
          const dataList = this.tableData.length;
          this.tableConfig.total = resultData.data.total;
          this.$notify({
            type: 'success',
            message: dataList <1 ? '未查找到相关数据' : '成功获取' + dataList + '条数据'
          })
        }
      }).catch((onerror)=>{
        console.log(onerror);this.loading = false
      })
    },
    // 显示列 选择事件
    handleCheckedColumnChange() {
      this.tableLabel = this.tableColumnList.filter(columnItem => {
        let isTrue = false;
        for (let checkedcolumnItem of this.checkedColumnList) {
          if (checkedcolumnItem === columnItem.label) {
            isTrue = true;
          }
        }
        return isTrue;
      });
    },
    //table section 表格选中事件
    handleSelectionChange(val){
      this.tableSelected = val
    },
//--------------添加楼栋------------------------
    // 添加操作
    clickAddData() {
      this.dialogConfig.openType ='add';
      this.dialogConfig.dialogFormVisible=true;
      this.dialogFormLabel.splice(2,1,{
        model: "roomNumber",
        label: "房间号",
        width: "60"
      });
    },
    //批量添加
    clickAddsData(){
      this.dialogConfig.openType='adds';
      this.dialogConfig.dialogFormVisible=true;
      this.dialogFormLabel.splice(2,1,{
        model:'campusName',
        type:'textarea',
        label: "房间号",
        width:'80'
      });
    },
    //  编辑操作
    clickEditData(row) {
      this.dialogForm = {
        buildingName: row.buildingName,
        equipmentModel:row.equipmentModel,
        roomNumber: row.roomNumber,
        deviceID:row.equipmentIdentifier,
        remarks: row.remark,
        campusName: this.$store.getters.campus_echo(row.campusName)
      };
      this.dialogConfig.openType ='edit';
      this.dialogConfig.dialogFormVisible=true;
    },
    //-----------------Dialog------------------
    //提交dialog表单、新增楼栋、批量添加楼栋、编辑楼栋
    submitDialogForm(formData){
      // add:添加  adds：批量添加  edit：编辑
      this.dialogForm.campusName = this.dialogForm.campusName[1]
      const openType = this.dialogConfig.openType;
      if (openType === 'add' ){
        //默认的体提交
        const Data = {
          buildingID:formData.buildingID,
          buildingName:formData.buildingName,
          // campusId:formData.campusId,
          schoolName:formData.schoolName,
          remark:formData.remark
        }
        // console.log(Data)
        addRoom(Data).then(res=>{

          if (res.data.code === 200){
            this.$message.success(res.data.message);
            this.getTableData(1,this.tableConfig.size,{});
            this.dialogConfig.dialogFormVisible=false;
          }
          else {
            this.$message.error(res.data.message);
          }
        }).catch(e=>{
          console.log(e);
        });
      }
      //批量提交的提交事件
      if (openType === 'adds'){
        const a = (Names) => {
          return  Names.split(";");
        }
        const Dates = {
          buildingName:a(this.dialogForm.buildingName),
          buildingID:formData.buildingID,
          campusId:formData.campusId,
          schoolName:formData.schoolName,
          remark:formData.remark
        }
        addRooms(Dates).then(res=>{
          if (res.data.success === true){
            this.$message.success(res.data.message);
            this.getTableData(1,this.tableConfig.size,{});
            this.dialogConfig.dialogFormVisible=false;
          }
        })
      }
      //编辑的提交
      else {
        const Data = {
          buildingID:formData.buildingID,
          buildingName:formData.buildingName,

          // campusId:formData.campusId, 表格数据缺少，与后端协商
          schoolName:formData.schoolName,
          remark:formData.remarks
        }
        // console.log(Data);
        editRoom(formData.buildingID,Data).then(res=>{
          if (res.data.success === true){
            this.$message.success(res.data.message);
            this.getTableData(1,this.tableConfig.size,{});
            this.dialogConfig.dialogFormVisible=false;
          }
        })
      }
    },
    //---------------检索--------------------
    searchBuilding (searchForm){
      const Data = {};
      for (let i in searchForm) {
        if (searchForm[i] !== "") {
          Data[i] = searchForm[i];
        }
      }
      //参数为空
      if (Object.keys(Data).length===0) {
        return this.$notify({
          type: 'warning',
          message: '查询参数为空'
        })
      }
      getRoomList(1,this.tableConfig.size,Data).then(res=>{
        let result = res.data
        if (result.success){
          //更新数据
          this.tableData = result.data.records;
          let dataList = result.data.total;
          this.tableConfig.total = result.data.total;
          return this.$notify({
            type: 'success',
            message: dataList <1 ? '未查找到相关数据' : '成功获取' + dataList + '条数据'
          })
        }else {
          return  this.$notify({
            type: 'warning',
            message: '查询失败!'
          })
        }
      }).catch((err)=>{
        console.log(err)
        return  this.$notify({
          type: 'error',
          message: '网络出错，请稍后再试'
        })
      })
    },
    resetData(){
      //重置
      this.searchForm = this.$options.data().searchForm;
    },
    //删除房间
    getDeleteReady(roomList){
      let IDList = []
      roomList.map(item=>{
        return  IDList.push(item.roomNumber)
      })
      delRoom(IDList).then((res)=>{
        const result = res.data
        if(result.code == 200){
          this.$notify({
            type:'success',
            message:'删除成功'
          })
          //重新拉取数据
          this.getTableData(1,this.tableConfig.size,{});
        }else {
          return  this.$notify({
            type:'error',
            message:result.message
          })
        }
      }).catch(function (){
        this.$notify({
          type:'error',
          message:'未能所选删除数据'
        })
      })
    }
  }
}
</script>

<style>
.mainBtn{
  width: 100%;
  position: relative;
  margin: 30px 0 20px;
}
.mainBtn button{
  margin-left:10px;
}
.searchDiv {
  margin: 10px 0;
}
.showColumnBtn {
  position: absolute;
  right: 0;
}
</style>
